const ArticleModel = require('../model/article')
const {marked} = require('marked')

module.exports = {
  async create(ctx, next) {
    if (ctx.method === 'GET') {
      await ctx.render('create', {
        title: '新建文章'
      })
    } else {
      // 发布文章
      const { title, content } = ctx.request.body
      let errMsg = ''
      if (title === '') {
        errMsg = '标题不能为空'
      } else if (content === '') {
        errMsg = '内容不能为空'
      }

      if (errMsg) {
        ctx.flash = { warning: errMsg }
        ctx.redirect('back')
      } else { // 写入数据库
        const article = Object.assign(ctx.request.body, {
          author: ctx.session.user._id
        })
        const result = await ArticleModel.create(article)
        // console.log(result);
        ctx.flash = { success: '文章发布成功' }
        ctx.redirect('/')
      }
    }
  },
  async detail(ctx, next) {
    const id = ctx.params.id
    if (id.length !== 24) {
      ctx.throw(404, '该文章不存在或已被删除')
    }

    // 查找文章数据且把关联的表数据都取到
    const article = await ArticleModel.findById(id).populate([
      { path: 'author', select: 'name' }
    ])
    content = marked(article.content)

    await ctx.render('article', {
      title: article.title,
      article,
      content
    })

    // console.log(article);
  }
}